﻿using UnityEngine;
using UnityEngine.UI;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Extension;
using System.Reflection;
using System.Reflection.Extension;
using System;

public class LinkCatch
{
    public MemberInfo source, destination;
    public object sourceParent, destinationParent;
    bool catched;

    public LinkCatch(Connection connection, Link link)
    {
        sourceParent = connection.source.GetParent(link.sourcePath);
        destinationParent = connection.destination.GetParent(link.destinationPath);
        source = connection.source.GetChildMemberInfo(link.sourcePath);
        destination = connection.destination.GetChildMemberInfo(link.destinationPath);
        calcCanCatch();
    }
    private void calcCanCatch()
    {
        catched = source.isNotNull() && destination.isNotNull() && sourceParent.isNotNull() && destinationParent.isNotNull();
    }
    public LinkCatch(object source, object destination, MemberLink link)
    {
        sourceParent = source.GetParent(link.sourcePath);
       // Debug.Log("Source " + source + ", sPath " + link.sourcePath + ", " + sourceParent);

        destinationParent = destination.GetParent(link.destMemberPath, link.destChildPath);
        this.source = source.GetChildMemberInfo(link.sourcePath);
        this.destination = destination.GetChildMemberInfo(link.destMemberPath, link.destChildPath);
        calcCanCatch();
    }
    public void Sync()
    {
        if (catched)
        {
            object value = source.GetValue(sourceParent);
            destination.SetValue(destinationParent, value);
        }
    }
}

[Serializable]
public class Connection
{
    public UnityEngine.Object source, destination;
    public List<Link> links;

    public List<LinkCatch> Sync()
    {
        List<LinkCatch> result = new List<LinkCatch>();
        links.ForEach(link =>
        {

            object sourceVal = source.GetValue(link.sourcePath);
           // bool isResource = destination is RawImage;
           
            destination.SetValue(sourceVal, link.destinationPath, string.Empty);

            if(link.continousUpdate)
                result.Add(new LinkCatch(this, link));
        });
        return result;
    }
}
[Serializable]
public class Link
{
    public string sourcePath, destinationPath;
    public bool continousUpdate, conditionalUpdate, localize;
}
[Serializable]
public class Control
{
    public List<Connection> connections;
    public List<LinkCatch> Sync()
    {
        List<LinkCatch> result = new List<LinkCatch>();
        connections.ForEach(connection =>
        {
            result.AddRange( connection.Sync());
        });
        return result;
    }
}
